<template>
  <div class="content">
    <div class="scroll-view-box" v-loading="submitBtn">
      <div class="user-title-box">填写内容</div>
      <el-form label-width="120px" :inline="true" :model="addForm" :rules="addRules" ref="addRules" label-position="top"
        :key="addForm.type">
        <el-form-item label="合同类型" prop="type">
          <el-select filterable @change="addTypeChangeFunc" v-model="addForm.type" placeholder="请选择合同类型"
            class="input-width">
            <el-option label="施工合同" :value="1"></el-option>
            <el-option label="勘场合同" :value="2"></el-option>
            <el-option label="增减项合同" :value="3"></el-option>
            <el-option label="定金合同" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="project_id">
          <el-select filterable @change="projectChangeFunc" v-model="addForm.project_id" placeholder="选择项目名称" clearable
            class="input-width">
            <el-option v-for="item in projectList" :key="item.id" :label="item.project_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签约主体" prop="signing_company_id">
          <el-select filterable @change="signingCompanyFunc" v-model="addForm.signing_company_id" placeholder="选择签约主体"
            clearable class="input-width">
            <el-option v-for="item in companyList" :key="item.id" :label="item.account_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同开工日期" prop="contract_commencement_date" v-if="addForm.type == 1 || addForm.type == 3">
          <el-date-picker value-format="yyyy-MM-dd" @change="dateChangeFunc($event, 'start')"
            :picker-options="pickerOptionsStart" class="input-width" v-model="addForm.contract_commencement_date"
            type="date" placeholder="选择合同开工日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同完工日期" prop="contract_completion_date" v-if="addForm.type == 1 || addForm.type == 3">
          <el-date-picker :disabled="!addForm.contract_commencement_date" :picker-options="pickerOptionsEnd"
            value-format="yyyy-MM-dd" @change="dateChangeFunc($event, 'end')" class="input-width"
            v-model="addForm.contract_completion_date" type="date" placeholder="选择合同完工日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同工期" prop="contract_duration_days" v-if="addForm.type == 1 || addForm.type == 3">
          <el-input disabled v-input-limit="1" v-model="addForm.contract_duration_days" placeholder="输入合同工期" clearable
            class="input-width">
            <template slot="suffix">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="合同签约日期" prop="signing_date">
          <el-date-picker value-format="yyyy-MM-dd" class="input-width" v-model="addForm.signing_date" type="date"
            placeholder="选择合同签约日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="签约金额" prop="contract_price">
          <el-input :disabled="addForm.type == 1 && Number(addForm.discount_amount) != 0" @change="jsWkFunc"
            v-input-limit="2" v-model="addForm.contract_price" placeholder="输入签约金额" clearable class="input-width">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="首期款金额" prop="down_payment" v-if="addForm.type == 1">
          <el-input @change="jsWkFunc" v-input-limit="2" v-model="addForm.down_payment" placeholder="输入首期款金额" clearable
            class="input-width">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="进度款金额" prop="progress_payment" v-if="addForm.type == 1">
          <el-input @change="jsWkFunc" v-input-limit="2" v-model="addForm.progress_payment" placeholder="输入进度款金额"
            clearable class="input-width">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="尾款金额" prop="balance_payment" v-if="addForm.type == 1">
          <el-input disabled v-input-limit="2" v-model="addForm.balance_payment" placeholder="输入尾款金额" clearable
            class="input-width">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="报价金额" prop="" v-if="addForm.type == 1">
          <el-input disabled v-input-limit="2" v-model="addForm.system_quotation" placeholder="" clearable
            class="input-width">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠金额" prop="" v-if="addForm.type == 1">
          <el-input disabled v-input-limit="2" v-model="addForm.discount_amount" placeholder="" clearable
            class="input-width">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="关联定金合同" prop="earnest_money_contract_id" v-if="addForm.type == 1">
          <el-select :disabled="!DJcontractList.length" filterable v-model="addForm.earnest_money_contract_id"
            :placeholder="DJcontractList.length ? '选择关联定金合同' : '无数据'" clearable class="input-width">
            <el-option v-for="item in DJcontractList" :key="item.id" :label="item.contract_number" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="已付金额" prop="" v-if="addForm.type == 1">
          <el-input disabled v-input-limit="2" v-model="dataObj.paid_amount" placeholder="" clearable
            class="input-width">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="签约备注" prop="remark">
          <el-input v-model="addForm.remark" placeholder="输入签约备注" clearable class="input-width">
          </el-input>
        </el-form-item>
        <el-form-item label="合同附件" prop="contract_file">
          <div class="file-list-box">
            <el-upload accept=".zip,.ppt,.ppsx,.pptx,.pdf" class="avatar-uploader" action="#" :show-file-list="false"
              :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                change_file(file, fileList, 'contract_file')
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="file-item-box" v-for="(item, index) in addForm.contract_file" :key="index">
              <div class="el-icon-delete-box" @click="delFileFunc('contract_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name || item.file_name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
              </el-tooltip>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="报价单" :prop="addForm.type == 1 ? 'quotation_file' : ''">
          <div class="file-list-box">
            <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" class="avatar-uploader" action="#" :show-file-list="false"
              :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                change_file(file, fileList, 'quotation_file')
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="file-item-box" v-for="(item, index) in addForm.quotation_file" :key="index">
              <div class="el-icon-delete-box" @click="delFileFunc('quotation_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name || item.file_name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
              </el-tooltip>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="利润单" :prop="addForm.type == 1 ? 'profit_statement_file' : ''">
          <div class="file-list-box">
            <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" class="avatar-uploader" action="#" :show-file-list="false"
              :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                change_file(file, fileList, 'profit_statement_file')
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="file-item-box" v-for="(item, index) in addForm.profit_statement_file" :key="index">
              <div class="el-icon-delete-box" @click="delFileFunc('profit_statement_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name || item.file_name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
              </el-tooltip>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="工程量清单" :prop="addForm.type == 1 ? 'cost_list_file' : ''">
          <div class="file-list-box">
            <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" class="avatar-uploader" action="#" :show-file-list="false"
              :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                change_file(file, fileList, 'cost_list_file')
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="file-item-box" v-for="(item, index) in addForm.cost_list_file" :key="index">
              <div class="el-icon-delete-box" @click="delFileFunc('cost_list_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name || item.file_name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
              </el-tooltip>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit('addRules')" :loading="submitBtn">提交</el-button>
        <el-button @click="cancelFunc">关闭</el-button>
      </span>
    </div>
  </div>
</template>
<script>
import common from "@/api/common";
import companyApi from "@/api/companyApi";
import proContractApi from "@/api/proContractApi";
import * as math from "mathjs";
export default {
  name: 'addContract',
  data() {
    var contractFilePass = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error('请上传合同附件'));
      } else {
        callback();
      }
    };
    var quotation_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error('请上传报价单'));
      } else {
        callback();
      }
    };
    var profit_statement_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error('请上传利润单'));
      } else {
        callback();
      }
    };
    var cost_list_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error('请上传工程量清单'));
      } else {
        callback();
      }
    };
    return {
      // **********************添加装修合同**************************
      pickerOptionsStart: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },//开工日期限制
      pickerOptionsEnd: {},//完工日期限制
      companyList: [],//主体列表
      projectList: [],//项目列表
      dataObj: "",//项目详情
      DJcontractList: [],//定金合同列表
      addForm: {
        project_id: "",
        remark: "",
        type: 1,
        contract_commencement_date: "",
        contract_completion_date: "",
        contract_duration_days: "",
        contract_price: "",
        down_payment: "",
        progress_payment: "",
        balance_payment: "",
        signing_company_id: "",
        earnest_money_contract_id: "",
        contract_file: [],
        quotation_file: [],
        profit_statement_file: [],
        cost_list_file: [],
        signing_date: "",
      },
      addRules: {
        project_id: [
          {
            required: true,
            message: "请选择项目",
            trigger: "change",
          },
        ],
        contract_commencement_date: [
          {
            required: true,
            message: "请选择开工日期",
            trigger: "change",
          },
        ],
        contract_completion_date: [
          {
            required: true,
            message: "请选择完工日期",
            trigger: "change",
          },
        ],
        signing_date: [
          {
            required: true,
            message: "请选择合同签约日期",
            trigger: "change",
          },
        ],
        contract_duration_days: [
          {
            required: true,
            message: "请输入合同工期",
            trigger: "change",
          },
        ],
        contract_price: [
          {
            required: true,
            message: "请输入签约金额",
            trigger: "change",
          },
        ],
        down_payment: [
          {
            required: true,
            message: "请输入首期款",
            trigger: "change",
          },
        ],
        progress_payment: [
          {
            required: true,
            message: "请输入进度款",
            trigger: "change",
          },
        ],
        balance_payment: [
          {
            required: true,
            message: "请输入尾款",
            trigger: "change",
          },
        ],
        signing_company_id: [
          {
            required: true,
            message: "请选择主体账户",
            trigger: "change",
          },
        ],
        contract_file: [
          {
            validator: contractFilePass,
            required: true,
            trigger: "change",
          }
        ],
        quotation_file: [
          {
            validator: quotation_file,
            required: true,
            trigger: "change",
          }
        ],
        profit_statement_file: [
          {
            validator: profit_statement_file,
            required: true,
            trigger: "change",
          }
        ],
        cost_list_file: [
          {
            validator: cost_list_file,
            required: true,
            trigger: "change",
          }
        ]
      },
      submitBtn: false,
      changeList: [],//增减项列表
    };
  },
  computed: {
    hisList() {
      return this.$store.getters.routerHis;
    },
    path() {
      return this.$route.path;
    },
  },
  mounted() {
    this.getCompanyList();
    if (this.$route.query.activeName) {
      this.addForm.type = Number(this.$route.query.activeName);
    }
    this.selectProjectList(this.addForm.type);
  },
  methods: {
    // 拿到签约主体名称（日志用）
    signingCompanyFunc() {
      if (this.addForm.signing_company_id) {
        this.addForm.signing_company_name = this.companyList.find(
          item => item.id === this.addForm.signing_company_id
        )?.account_name || '';
      }
    },
    // 合同类型切换
    addTypeChangeFunc(typeVal) {
      this.addForm = {
        remark: "",
        type: typeVal,
        project_id: "",
        contract_commencement_date: "",
        contract_completion_date: "",
        contract_duration_days: "",
        contract_price: "",
        down_payment: "",
        progress_payment: "",
        balance_payment: "",
        signing_company_id: "",
        earnest_money_contract_id: "",
        contract_file: [],
        quotation_file: [],
        profit_statement_file: [],
        cost_list_file: [],
        signing_date: "",
      }
      this.dataObj = {};
      this.$nextTick(() => {
        this.$refs.addRules.clearValidate();
        this.selectProjectList(typeVal);
      })
    },
    // 合同列表
    getContractList(type, project_id) {
      proContractApi.getContractList({
        page: 1,
        num: 999,
        contract_type: 4,
        project_id
      }).then(res => {
        console.log(res, "合同列表", type)
        if (res.code == 200) {
          // 装修合同获取定金合同
          this.DJcontractList = res.data.list;
        }
      })
    },
    // 尾款计算
    jsWkFunc() {
      if (this.addForm.type != 1) return;
      let { down_payment, progress_payment, contract_price } = this.addForm;
      let { survey_fees } = this.dataObj;
      if (down_payment && progress_payment && contract_price) {
        // contract_price - (progress_payment + down_payment + survey_fees)
        let addNumber = math.format(
          math.add(
            math.bignumber(progress_payment)
            , math.bignumber(down_payment)
            , math.bignumber(survey_fees)
          )
        )
        let subNumber = math.format(
          math.subtract(
            math.bignumber(contract_price)
            , math.bignumber(addNumber)
          )
        )
        subNumber = Number(subNumber).toFixed(2).replace(/(\.0+|0+)$/, '');
        this.addForm.balance_payment = subNumber;
      } else {
        this.addForm.balance_payment = '';
      }
    },
    // 项目选择(装修合同/定金合同)
    projectChangeFunc() {
      if (!this.addForm.project_id) {
        this.addForm.contract_price = '';
        this.addForm.balance_payment = '';
        this.addForm.zxht_id = '';
        this.addForm.earnest_money_contract_id = '';
        this.addForm.system_quotation = '';
        this.dataObj = {};
        if (this.addForm.type == 1) {
          this.addForm.signing_company_id = '';
        }
        return;
      }

      // 获取项目名称
      this.addForm.project_name = this.projectList.find(
        item => item.id === this.addForm.project_id
      )?.project_name || '';

      // // 获取项目编号
      this.addForm.project_number = this.projectList.find(
        item => item.id === this.addForm.project_id
      )?.project_number || '';

      // 获取主体名称
      let index = this.projectList.findIndex(item => {
        return item.id == this.addForm.project_id;
      })
      this.addForm.signing_company_id = this.projectList[index].receiving_account_id || '';
      // 拿到签约主体名称（日志用）
      this.signingCompanyFunc();

      // 装修合同时获取相关的定金合同
      if (this.addForm.type == 1) {
        this.getContractList(this.addForm.type, this.addForm.project_id);
      }

      // 获取项目详情
      this.selectProjectDetails(this.addForm.project_id, (data) => {
        console.log(data, "详情", data.system_quotation, data.discount_amount)
        if (this.addForm.type == 1) {

          let contract_price = math.format(
            math.subtract(
              math.bignumber(data.system_quotation)
              , math.bignumber(data.discount_amount)
            )
          )
          this.addForm.system_quotation = data.system_quotation;
          this.addForm.discount_amount = data.discount_amount;

          this.addForm.contract_price = Number(contract_price);
        }
        this.addForm.balance_payment = '';
        this.jsWkFunc();//计算尾款
      })
    },
    // 项目详情
    selectProjectDetails(project_id, cb) {
      common.selectProjectDetails({
        project_id
      }).then(res => {
        console.log(res, "项目详情")
        if (res.code == 200) {
          this.dataObj = res.data;
          cb && cb(res.data)
        }
      })
    },
    // 项目列表
    selectProjectList(type) {
      common.selectProjectList({
        less_status: [1150],
        greater_status: type == 1 ? [1095] : []
      }).then(res => {
        console.log(res, "项目列表")
        this.projectList = res.data;
      })
    },
    // 主体列表
    getCompanyList() {
      companyApi.getCompanyList({
        account_type: 1,
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, '主体列表')
        if (res.code == 200) {
          this.companyList = res.data.list;
        }
      })
    },
    // 开工完工日期选择
    dateChangeFunc(val, type) {
      console.log(val, type)
      let that = this;
      // 清空完工日期
      if (!val && type == 'start') {
        that.addForm.contract_completion_date = '';
      }
      // 处理完工日期选择区间
      if (val && type == 'start') {
        that.pickerOptionsEnd = {
          disabledDate(time) {
            return time.getTime() < new Date(val).getTime();;
          }
        }
      }
      // 日期处理
      if (
        that.addForm.contract_commencement_date &&
        that.addForm.contract_completion_date
      ) {
        const date1 = new Date(that.addForm.contract_commencement_date);
        const date2 = new Date(that.addForm.contract_completion_date);
        if (!that.compareDates(date1, date2)) {
          that.$message.warning("完工日期需晚于开工日期");
          type == "start"
            ? (that.addForm.contract_commencement_date = "")
            : (that.addForm.contract_completion_date = "");
          that.addForm.contract_duration_days = "";
          return;
        }
        that.addForm.contract_duration_days = that.daysBetween(date1, date2) + 1;
      } else {
        that.addForm.contract_duration_days = '';
      }

    },
    // 两日期差值
    daysBetween(date1, date2) {
      const oneDay = 24 * 60 * 60 * 1000; // 每天的毫秒数
      const firstTime = date1.getTime();
      const secondTime = date2.getTime();

      return Math.round(Math.abs((firstTime - secondTime) / oneDay));
    },
    // (开工早与完工判断)
    compareDates(date1, date2) {
      return date1.getTime() - date2.getTime() < 0;
    },
    // 文件选择
    change_file(file, list, type) {
      console.log(file, type);
      this.addForm[type] = [file];
      this.$refs.addRules.validateField(type);
    },
    // 文件删除
    delFileFunc(type) {
      this.addForm[type] = [];
      this.$refs.addRules.validateField(type);
    },
    // 添加合同
    addContract(obj) {
      this.submitBtn = true;
      proContractApi.addContract(obj).then(res => {
        console.log(res, "添加合同")
        this.submitBtn = false;
        if (res.code == 200) {
          this.cancelFunc();
        }
        if (res.code == 6064) {
          this.$confirm('优惠已超出权限，是否跳转申请优惠?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$goBackTab(this, () => {
              this.$router.push({ path: '/addDiscount' });
            });
          }).catch(() => {
          });
          return;
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 提交
    saveSubmit(formName) {
      let addForm = this.addForm;
      console.log(addForm, "参数")
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formdata = new FormData();
          let obj = {
            contract_type: addForm.type || '',
            project_id: addForm.project_id || '',
            contract_commencement_date: addForm.contract_commencement_date || '',
            contract_completion_date: addForm.contract_completion_date || '',
            contract_duration_days: addForm.contract_duration_days || '',
            contract_price: addForm.contract_price || '',
            down_payment: addForm.down_payment || '',
            progress_payment: addForm.progress_payment || '',
            balance_payment: addForm.balance_payment || '',
            signing_company_id: addForm.signing_company_id || '',
            signing_company_name: addForm.signing_company_name || '',
            earnest_money_contract_id: addForm.earnest_money_contract_id || '',
            signing_date: addForm.signing_date || '',
            remark: addForm.remark || ''
          }
          formdata.append('data', JSON.stringify(obj))
          addForm.contract_file.forEach(item => {
            formdata.append('contract_file[]', item.raw);
          })
          addForm.quotation_file.forEach(item => {
            formdata.append('quotation_file', item.raw);
          })
          addForm.profit_statement_file.forEach(item => {
            formdata.append('profit_statement_file', item.raw);
          })
          addForm.cost_list_file.forEach(item => {
            formdata.append('cost_list_file', item.raw);
          })
          this.addContract(formdata);
        } else {
          return false;
        }
      });
    },
    // 取消
    cancelFunc() {
      this.$goBackTab(this);
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
@import "@/styles/addPage.scss";
</style>
<style lang="scss">
.labelClassName {
  width: 160px;
  background: #f5f8fe !important;
  text-align: center !important;
  padding: 0 !important;
  line-height: 1 !important;
}

.contentClassName {
  font-weight: 400 !important;
  font-size: 17px !important;
  color: #1b2431 !important;
  padding-left: 20px !important;
}

.labelClassName2 {
  width: 160px;
  background: rgba(0, 0, 0, 0) !important;
  text-align: center !important;
  padding: 0 !important;
  line-height: 1 !important;
  border: none !important;
}

.contentClassName2 {
  font-weight: 400 !important;
  font-size: 17px !important;
  color: #1b2431 !important;
  padding-left: 20px !important;
  border: none !important;
}

.labelClassName3 {
  width: 160px;
  background: rgba(0, 0, 0, 0) !important;
  text-align: center !important;
  padding: 0 !important;
  line-height: 1 !important;
  border: none !important;
  opacity: 0;
}

.contentClassName3 {
  font-weight: 400 !important;
  font-size: 17px !important;
  color: #1b2431 !important;
  padding-left: 20px !important;
  border: none !important;
  opacity: 0;
}
</style>